import pymongo
from .BaseRepository import BaseRepository
from bson.objectid import ObjectId
import time
class GameRepository(object):
    def __init__(self, db_name) -> None:
        self.baseRep = BaseRepository(collectionname=db_name)

    def get_need_save(self) -> list:
        results, nums, _ = self.baseRep.get_all_no_page(
            sort=["update", pymongo.DESCENDING])
        print(nums)
        results = [r for r in results if r.get(
            "status", "need_save") == "need_save"]
        return results

    def get_great_or_less_games(self, game_id: str, operator: str):
        results, nums, _ = self.baseRep.get_all_no_page(
            sort=["update", pymongo.DESCENDING])
        if operator == ">":
            results = [r for r in results if r.get("_id").generation_time >= ObjectId(game_id).generation_time]
        else:
            results = [r for r in results if r.get("_id").generation_time<= ObjectId(game_id).generation_time]
        return results

    def refresh_status(self) -> bool:
        results, nums, _ = self.baseRep.get_all_no_page(
            sort=["update", pymongo.DESCENDING])
        print(nums)
        for r in results:
            r["status"] = "need_save"
            self.baseRep.update_by_id(r.get("_id"), r)
            # print(r.get("name"))
            time.sleep(0.01)
        return True

    def update_status_saved(self, game_id) -> bool:
        r, num, _ = self.baseRep.get_by_id(game_id)
        if num > 0:
            r["status"] = "saved"
            self.baseRep.update_by_id(r.get("_id"), r)
            return True
        return False
